<template>
    <div class="main">
        <van-nav-bar title="编辑地址" left-text="返回" left-arrow @click-left="onClickLeft" />
        <div class="business">
            <div style="display: flex; align-items: center; padding-left: 20px;">
                <van-image style="width: 40px; height: 40px;" :src="businessinfo.businessImg" />
                <label style="margin-left: 10px; font-size: 25px; color: #333;font-weight: 550;color: #1989fa;">{{ businessinfo.businessName }}</label>
            </div>
            <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"></van-divider>

            <div v-for="item in cartItems" :key="item.foodId" style="margin-bottom: 10px;">
                <div style="display: flex; justify-content: space-between; align-items: center; padding-left: 20px;">
                    <div style="display: flex; align-items: center;">
                        <van-image width="40" height="40" :src="item.foodImg" style="margin-right: 10px;" />
                        <label style="font-size: 16px;">{{ item.foodName }} x {{ item.quantity }}</label>
                    </div>
                    <div style="font-size: 18px; color: #1989fa;margin-right: 15px;">￥{{ item.foodPrice }}</div>
                </div>
                <van-divider style="color: #f6f6f6; border-color: #f6f6f6; margin: 0 16px;"></van-divider>
            </div>

            <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"></van-divider>
            <div
                style="display: flex; flex-direction: column-reverse; align-items: flex-end; font-size: 15px;padding-right: 10px;">
                <label>实付：￥{{ finalPrice }}</label>
                <label>总计：￥{{ totalPrice }}, 配送费：￥{{ businessinfo.deliveryPrice }}</label>
            </div>
        </div>
        <div class="address">
            <van-cell :title="contactAddress()" :label="contact" is-link @click="toSelect" />
        </div>
        <div class="pay">
            <van-collapse v-model="activeNames">
                <van-collapse-item title="支付方式" name="1">
                    <van-radio-group v-model="checked">
                        <van-radio name="1">
                            <div style="display: flex; align-items: center;">
                                <van-icon size="30px" color="#1989fa" name="alipay" />
                                <label>支付宝支付</label>
                            </div>

                        </van-radio>

                    </van-radio-group>
                </van-collapse-item>
            </van-collapse>
        </div>
        <div ref="alipayForm"></div>
        <div>
            <van-submit-bar :disabled="disabled" :loading="isLoading" button-text="去支付" :price="finalPrice * 100"
                @submit="onSubmit" />
        </div>

    </div>

</template>

<script>
import { ref, reactive, toRefs, computed } from 'vue';
import { showSuccessToast } from 'vant';
import { useRouter, useRoute } from 'vue-router';
import { listAddress, getBusinessById, getCartByBusinessId, pay, submitOrder } from '../api/index';

export default {
    setup() {
        const isLoading = ref(false);
        const disabled = ref(false);
        const activeNames = ref(['1']);
        const checked = ref('1');
        const router = useRouter();
        const route = useRoute();
        const businessid = route.query.businessid
        const businessinfo = ref([])
        const cartItems = ref([])
        const initBusinessInfo = async () => {
            try {
                const response = await getBusinessById(businessid);
                businessinfo.value = response.data;
                console.log(businessinfo.value)
            } catch (error) {
                console.error('获取商家信息时出错:', error);
            }
        };
        initBusinessInfo()

        const getCart = async () => {
            try {
                const response = await getCartByBusinessId(businessid);
                cartItems.value = response.data.records;
                console.log(cartItems.value)
            } catch (error) {
                console.error('获取购物车时出错:', error);
            }
        };
        getCart()
        const alipayForm = ref();
        const getAddressList = async (pageNum, pageSize) => {
            try {
                const response = await listAddress({
                    pageNum: pageNum,
                    pageSize: pageSize
                });
                console.log(response.data.records[0]);
                state.addressList[0].address = response.data.records[0].address
                state.addressList[0].contactName = response.data.records[0].contactName
                state.addressList[0].contactSex = response.data.records[0].contactSex
                state.addressList[0].contactTel = response.data.records[0].contactTel
                state.addressList[0].daId = response.data.records[0].daId

            } catch (error) {
                console.error('获取地址时出错:', error);
            }
        };

        getAddressList(1, 5);
        const state = reactive({
            addressList: [{
                address: '',
                contactName: '',
                contactSex: '',
                contactTel: '',
                daId: '',
                userId: ''
            }],
            // curAddress: route.query.address
            curAddressId: route.query.addressId,
            curAddress: route.query.address,
            curAddressName: route.query.addressName,
            curAddressTel: route.query.addressTel
        })

        const contactAddress = () => {
            if (state.curAddress == null) {

                return state.addressList[0].address
            }
            return state.curAddress
        }

        const contact = computed(() => {
            if (state.curAddressName == null && state.curAddressTel == null) {
                return state.addressList[0].contactName + " " + state.addressList[0].contactTel
            }
            return state.curAddressName + " " + state.curAddressTel
        })

        const contactId = () => {
            if (state.curAddressId == null) {
                return state.addressList[0].daId
            }
            return state.curAddressId
        }

        const onSubmit = () => {
            isLoading.value = true;
            disabled.value = true;
            setTimeout(() => {
                isLoading.value = false;
                disabled.value = false;

                submitOrder({
                    businessId: businessid,
                    daId: contactId(),
                    deliveryCharge: businessinfo.value.deliveryPrice
                })
                    .then(function (response) {
                        console.log(response);
                        if (response.code == 2000) {
                            showSuccessToast('提交订单成功');
                            pay({
                                orderId: response.data
                            })
                                .then(function (response) {

                                    console.log(response);
                                    alipayForm.value.innerHTML = response; // 假设response.data包含HTML内容

                                    window.document.forms[0].submit();

                                })
                                .catch(function (error) {
                                    console.error(error);
                                });
                        }
                    })

            }, 1000);
        }

        const onClickLeft = () => router.back();

        const toSelect = () => {
            router.push({ path: '/addressselect', query: { businessid: businessid } })
        }

        // 总计价格

        const totalPrice = computed(() => {

            return cartItems.value.reduce((sum, item) => sum + (item.foodPrice * item.quantity), 0);

        });


        // 实付价格，总计价格加上配送费

        const finalPrice = computed(() => {

            return totalPrice.value + businessinfo.value.deliveryPrice;

        });

        return {
            onSubmit,
            isLoading,
            disabled,
            onClickLeft,
            activeNames,
            checked,
            contact,
            contactAddress,
            contactId,
            ...toRefs(state),
            toSelect,
            alipayForm,
            businessid,
            businessinfo,
            initBusinessInfo,
            cartItems,
            getCart,
            totalPrice,
            finalPrice

        };
    },
};
</script>

<style scoped>
.business {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    /* display: flex; */
    justify-content: left;

    margin: 20px;
    padding: 10px;

}

.address {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin: 20px;
}

.pay {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin: 20px;
}

.main {
    background-color: white;
    padding-bottom: 80px;
    overflow-y: auto;
}

.gradientButton {
    background-image: linear-gradient(to right, #666666, #ffad06);
    border: none;
}
</style>